package com.stephen.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Created by stephen on 2021-03-30 21:21 .
 * Description: 生成图片验证码
 */
public class ImageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 让浏览器3秒自动刷新一次
        resp.setHeader("refresh","3");
        // 在内存中创建一个图片
        BufferedImage image = new BufferedImage(120, 30, BufferedImage.TYPE_INT_RGB);
        // 画笔
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        // 设置图片背景颜色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,120,30);
        // 给图片写数据
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font(null,Font.BOLD,30));
        graphics.drawString(generateNum(),0,30);

        // 告诉浏览器,该请求以图片的方式打开
        resp.setContentType("image/jpeg");
        // 网站存在缓存,不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        // 把图片写给浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());

    }

    // 生成7位随机数
    private String generateNum() {
        String num = new Random().nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7 - num.length(); i++) {
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }

}
